import 'dart:async';

import 'package:basePigeons/pigeons.dart';
import 'package:basePigeons/pigeons_model/pigeons_model.dart';
import 'package:flutter_getx/utils/flutter_api_impl.dart';
import 'package:flutter_getx/utils/http.dart';
import 'package:flutter_getx/utils/toast.dart';
import 'package:flutter_getx/utils/token.dart';
import 'package:get/get.dart';

import 'state.dart';

class LoginLogic extends GetxController {
  final LoginState state = LoginState();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();

    FlutterApi.setup(FlutterApiImpl());
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  // 1. 实现倒计时
  Timer? timer;
  void startCountdown() {
    if (state.isCountingDown.value) {
      return;
    }
    state.isCountingDown.value = true;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (state.countdown.value > 0) {
        state.countdown.value--;
      } else {
        state.isCountingDown.value = false;
        state.countdown.value = 60;
        timer.cancel();
      }
    });
  }

  // 2. 获取验证码
  void getVerificationCode() async {
    // 2.1 校验手机号
    if (state.phoneController.value.text.isEmpty) {
      return ToastUtil.showError('请输入手机号码');
    }

    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(state.phoneController.value.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }

    // 2.2 调用获取验证码接口
    var res = await http.get('/code', params: {
      'mobile': state.phoneController.value.text,
    });
    try {
      // 2.3 开始倒计时
      startCountdown();
      if (res['code'] != 10000) return ToastUtil.showError('获取验证码失败');
      ToastUtil.showSuccess('验证码已发送');
      // 延迟执行
      Future.delayed(const Duration(seconds: 1), () {
        state.codeController.value.text = res['data']['code'] as String;

        state.isCountingDown.value = false;
        state.countdown.value = 60;
        timer?.cancel();
      });
    } catch (e) {
      state.isCountingDown.value = false;
      state.countdown.value = 60;
      timer?.cancel();
      ToastUtil.showError('获取验证码失败');
    }
  }

// 提交登录信息
  void submit() async {
    try {
      String platformVersion = await Pigeons().getPlatformVersion();
      print('平台版本: $platformVersion');
      ToastUtil.showSuccess('鸿蒙方法调用成功: $platformVersion');

      // 测试：5秒后鸿蒙层会主动调用Flutter的sessionInvalid方法
      print('5秒后鸿蒙层将主动调用Flutter的sessionInvalid方法');
    } catch (e) {
      print('调用鸿蒙方法失败: $e');
      ToastUtil.showError('调用鸿蒙方法失败: $e');
    }

    if (state.phoneController.value.text.isEmpty) {
      return ToastUtil.showError('请输入手机号码');
    }
    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(state.phoneController.value.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }
    if (state.codeController.value.text.isEmpty) {
      return ToastUtil.showError('请输入验证码');
    }
    if (state.codeController.value.text.length != 6) {
      return ToastUtil.showError('请输入6位验证码');
    }
    RegExp regExp2 = RegExp(r'^\d{6}$');
    if (!regExp2.hasMatch(state.codeController.value.text)) {
      return ToastUtil.showError('请输入6位验证码');
    }

    var res = await http.post('/login', {
      'mobile': state.phoneController.value.text,
      'code': state.codeController.value.text,
    });

    if (res['code'] != 10000) return ToastUtil.showError('登录失败');
    try {
      TokenManager().saveToken(res['data']['token'] as String);
      ToastUtil.showSuccess('登录成功');
      Get.offAllNamed('/');
    } catch (e) {
      ToastUtil.showError('登录失败');
    }

    // Navigator.pop(context);
  }
}
